<?php
/**
 * Created by PhpStorm.
 * User: 悟能科技
 * Date: 2018/8/27
 * Time: 16:43
 */

namespace app\merchant\controller;


use app\common\controller\AdminBase;
use app\common\controller\Platurl;
use app\common\controller\TestBase;
use app\common\model\Agent;
use app\common\model\CardBizPut;
use app\common\model\CardMember;
use app\common\model\CardQrcode;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use think\Controller;
use think\Debug;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardusextendtest extends Controller
{

    //开卡组件二维码
    public function cardusbizqrcode(Request $request){
        $param = $request->param();
        $CardQrcode = new CardQrcode();
        $map['c_id'] = $param['c_id'];
        $list = $CardQrcode->where($map)->paginate(20);
        $card['c_id'] = $param['c_id'];
        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //开卡
    public function cardusbizadd($param){
        Debug::remark('begin');
        $CardMember = new CardMember();
        $cardinfo = $CardMember->where(['id' => $param['c_id']])->field('card_id,mid,id')->find();
        $data['card_id'] = $cardinfo['card_id'];
        $data['outer_str'] = $param['outer_str'];
        $options = $this->options($cardinfo['card_id']);
        $weObj = new Wxobjopen($options);
        $res = $weObj->geturlActivate($data);
        if ($res['errcode'] == 0){
            //存储数据
            $CardQrcode = new CardQrcode();
            $dates['top_mid'] = Session::get('login_top_mid');
            $dates['mid'] = $param['outer_str'];
            $dates['c_id'] = $cardinfo['id'];
            $dates['card_id'] = $cardinfo['card_id'];
            $dates['url'] = $res['url'];
            $dates['type'] = 1;
            $dates['outer_str'] = $param['outer_str'];
            $dates['create_time'] = time();
            $CardQrcode->allowField(true)->save($dates);
            //END
            $id = $CardQrcode->id;
            $Platurl = new Platurl();
            $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
            $dataa['url_mobile'] = $url['platurl'].'/mobile.php?s=/cardopen/index/type/BIZ/qrcode/'.$id;
            $dataa['qrcode_url'] = $url['platurl'].'/bizcard/'.$id.'.png';
            $CardQrcode->save($dataa,['id'=>$id]);
            $this->scbizqrcode($id);
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '成功';
            $rarr['data'] = $res['url'];
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '成功';
        }else{
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '失败';
            $rarr['data'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $res['errmsg'];
        }
        Debug::remark('end');
        $rarr['begin_s'] = Debug::getRangeTime('begin','end').'s';
        return $rarr;
    }

    //开卡
    public function cardusbizcreate(Request $request){
        if ($request->isAjax()) {
            $param = $request->param();
            $CardMember = new CardMember();
            $cardinfo = $CardMember->where(['id' => $param['c_id']])->find('card_id,mid,id')->find();
            $data['card_id'] = $cardinfo['card_id'];
            $data['outer_str'] = $param['outer_str'];
            $options = $this->options($cardinfo['card_id']);
            $weObj = new Wxobjopen($options);
            $res = $weObj->geturlActivate($data);
            if ($res['errcode'] == 0){
                //存储数据
                $CardQrcode = new CardQrcode();
                $dates['top_mid'] = Session::get('login_top_mid');
                $dates['mid'] = $cardinfo['mid'];
                $dates['c_id'] = $cardinfo['c_id'];
                $dates['card_id'] = $cardinfo['card_id'];
                $dates['url'] = $res['url'];
                $dates['outer_str'] = $param['outer_str'];
                $dates['create_time'] = time();
                $CardQrcode->allowField(true)->save($dates);
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '成功';
                $rarr['data'] = $res['url'];
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '成功';
            }else{
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '失败';
                $rarr['data'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = $res['errmsg'];
            }
            return json($rarr);
        }else{

            return $this->fetch();
        }
    }

    public function scbizqrcode($id)
    {
        try {
            $CardQrcode = new CardQrcode();
            $cqrcode = $CardQrcode->where(['id' => $id])->field('url,url_mobile')->find();
            action('Qrcodes/cardbizqrcode', array($id, $cqrcode['url_mobile'] . ".html"));
//            $qr = $jg;
//            $length = filesize($qr);
//            $type = mime_content_type($qr);
//            $showname = ltrim(strrchr($qr, '/'), '/');
//            header("Content-Description: File Transfer");
//            header('Content-type: ' . $type);
//            header('Content-Length:' . $length);
//            if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
//                header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
//            } else {
//                header('Content-Disposition: attachment; filename="' . $showname . '"');
//            }
//            readfile($qr);
//        $url = request()->domain() .  "/bizcard/" . $param['id'] . '.png';
//        return json($url);
//            exit;
        }catch (\Exception $e) {

            $data['return_msg'] = $e->getMessage();
        }
    }


    public function getbizqrcode(Request $request)
    {
        $param = $request->param();
        $CardQrcode = new CardQrcode();
        $cqrcode = $CardQrcode->where(['id'=>$param['id']])->field('url,url_mobile')->find();
        $jg = action('Qrcodes/cardbizqrcode', array($param['id'],$cqrcode['url_mobile'] . ".html"));
        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
//        $url = request()->domain() .  "/bizcard/" . $param['id'] . '.png';
//        return json($url);
        exit;
    }


    //获取跟随推荐信息
    public function getbonusbizput(Request $request){
        $param = $request->param();
        $CardBizPut = new CardBizPut();
        $top_mid = Session::get('login_top_mid');
        $info = $CardBizPut->where(['top_mid'=>$top_mid])->find();
        if ($info){

            $rarr['code'] = 0;
            $rarr['data']['card'] = getgivecardid($info['c_id_list']);
            $rarr['data']['end_time'] = date("Y-m-d h:i:s",$info['end_time']);
            $rarr['message'] = 'SUCCESS';
        }else{
            $rarr['code'] = 9001;
            $rarr['data'] = '';
            $rarr['message'] = 'ERROR';
        }
        return json($rarr);

    }
    

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        Session::set('openid', null);
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $map['id'] = $CardMember->where('card_id', $card_id)->value('mid');
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}